package org.tgcloud.group.core.WXUtils.wxpay;

import org.tgcloud.group.core.BaseLogger;
import org.tgcloud.group.core.StringUtil;
import org.tgcloud.group.core.WXUtils.WeiConfig;
import org.tgcloud.group.core.WXUtils.alipay.AlipayCore;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 小程序支付参数
 */
public class SmallZhiRequest extends BaseLogger {

    private String timeStamp;

    private String nonceStr;

    private String prepayId;

    private String signType;

    private String appId;

    public SmallZhiRequest(String prepayId) {
        this.prepayId = prepayId;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 20;i++)
        {
            sb.append(StringUtil.getRandomChar());
        }
        this.nonceStr = sb.toString();
        this.timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        this.appId = WeiConfig.appId;
        this.signType = "MD5";
    }


    /**
     * 获取返回给手机端的响应
     *
     * @return
     */
    public Map<String,String> getTelResponse() {

        //除去数组中的空值和签名参数
//        appId=wxd678efh567hg6787
//        nonceStr=5K8264ILTKCH16CQ2502SI8ZNMTM67VS
//        package=prepay_id=wx2017033010242291fcfe0db70013231072
//        signType=MD5
//        timeStamp=1490840662
//        key=qazwsxedcrfvtgbyhnujmikolp111111
        Map<String, String> sPara = AlipayCore.paraFilter(getParams());
        //生成签名结果
        String mySign = StringUtil.MD5Encode(AlipayCore.createLinkStringNoYinHao(sPara) + "&key=" + WeiConfig.client_key).toUpperCase();
        //签名结果与签名方式加入请求提交参数组中
        try {
            sPara.put("paySign", URLEncoder.encode(mySign, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            logger.warn("encode出错");
            e.printStackTrace();
        }
        return sPara;
    }

    /*获得支付参数值字典*/
    public Map<String,String> getParams() {

        Map<String, String> sParaTemp = new HashMap<String, String>();
        sParaTemp.put("appId",this.appId);
        sParaTemp.put("nonceStr",this.nonceStr);
        sParaTemp.put("package","prepay_id=" + this.prepayId);
        sParaTemp.put("signType", this.signType);
        sParaTemp.put("timeStamp",this.timeStamp);
        return sParaTemp;
    }

}
